﻿Imports Entidad
Imports Negocio
Imports Utilitario
Public Class frmOrdenesCompraSIS

    Dim CIA As String = "01"
    Dim SUC As String = "01"
    Dim TDO As String = "OC"
    Dim servicio1 As New OrdenesCompraNegocio
    Dim servicio2 As New ArticuloNegocio
    Dim util As New Utiles

    Sub mostrarArticulo(codArticulo As String)
        Dim articulo As Articulo = servicio2.obtenerArticulo(codArticulo)

        If articulo Is Nothing Then
            util.mensaje("Ocurrió un error de conexión. Intentelo nn")
            Exit Sub
        End If

        If articulo.ART_Codigo = "-1" Then
            util.mensaje("Artículo no existe.")
            Exit Sub
        End If

        txtDescripcion.Text = articulo.ART_Descripcion
        txtUnidad.Text = articulo.UNM_Descripcion
        txtCantidad.Focus()
    End Sub

    Sub mostrarOrdenCompra(codOrden As String)
        Dim orden As OrdenCompra = servicio1.obtenerOrdenCompra(CIA, SUC, TDO, codOrden)

        If orden Is Nothing Then
            util.mensaje("Ocurrió un error de conexión. Intentelo nuevamente.")
            Exit Sub
        End If

        If orden.CIA = "-1" Then
            util.mensaje("No existe la orden de compra.")
            Exit Sub
        End If

        lblProveedor.Text = "(" & orden.PROV_Codigo & ") " & orden.PROV_Nombre
        lblFecLlegada.Text = orden.FechaLlegada
        lblFecRegistro.Text = orden.FechaRegistro
        lblCantItems.Text = orden.CANT_Items

        listarDetalleOrdenCompra(codOrden)
    End Sub

    Sub listarDetalleOrdenCompra(codOrden As String)
        Dim ds As DataSet = servicio1.obtenerOrdenesCompraDetalle(CIA, SUC, TDO, codOrden)

        If ds Is Nothing Then
            util.mensaje("Ocurrió un error al obtener el detalle. Intentelo nuevamente.")
            Exit Sub
        End If

        dgvOrdenCompra.Rows.Clear()

        For i = 0 To ds.Tables(0).Rows.Count - 1
            dgvOrdenCompra.Rows.Add(False, ds.Tables(0).Rows(i)("ART_Codigo").ToString.Trim, ds.Tables(0).Rows(i)("ART_Descripcion").ToString.Trim, ds.Tables(0).Rows(i)("UNM_Abreviatura").ToString.Trim,
                                    ds.Tables(0).Rows(i)("DPD_Costo").ToString.Trim, ds.Tables(0).Rows(i)("DPD_Cantidad").ToString.Trim, "")
        Next

        If ds.Tables(0).Rows.Count > 0 Then
            dgvOrdenCompra.Rows(0).Selected = False
        End If
    End Sub

    Private Sub btnBuscar_Click(sender As System.Object, e As System.EventArgs) Handles btnBuscar.Click
        mostrarOrdenCompra(txtOrdenCompra.Text.Trim)
    End Sub

    Private Sub txtOrdenCompra_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtOrdenCompra.KeyDown
        If e.KeyValue = Keys.Enter Then
            mostrarOrdenCompra(txtOrdenCompra.Text.Trim)
        End If
    End Sub

    Private Sub txtArticulo_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtArticulo.KeyDown
        If e.KeyValue = Keys.Enter Then
            mostrarArticulo(txtArticulo.Text.Trim)
        End If
    End Sub

    Private Sub btnAgregar_Click(sender As System.Object, e As System.EventArgs) Handles btnAgregar.Click
        If MsgBox("¿Está seguro de agregar este artículo?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Mensajes al Usuario") = MsgBoxResult.Yes Then
            agregarArticulo()
        End If
    End Sub

    Private Sub dgvOrdenCompra_CellClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvOrdenCompra.CellClick
        Dim f As Integer = e.RowIndex
        Dim c As Integer = e.ColumnIndex

        If f > -1 Then
            If c = 2 Then
                txtArticulo.Text = dgvOrdenCompra.Item("Column1", f).Value
                txtDescripcion.Text = dgvOrdenCompra.Item("Column2", f).Value
                txtUnidad.Text = dgvOrdenCompra.Item("Column3", f).Value
                txtCantidad.Value = dgvOrdenCompra.Item("Column5", f).Value
                txtCosto.Text = dgvOrdenCompra.Item("Column7", f).Value
            End If
        End If
    End Sub

    Sub operaciones(e As System.Windows.Forms.DataGridViewCellEventArgs)
        Dim f As Integer = e.RowIndex
        Dim c As Integer = e.ColumnIndex
        dgvOrdenCompra.EndEdit()

        If f > -1 Then
            If c = 0 Then
                If verificarChecksMarcados() < 2 Then
                    If Convert.ToBoolean(dgvOrdenCompra.Item(c, f).Value) = True Then
                        dgvOrdenCompra.Item(5, f).ReadOnly = False
                        If dgvOrdenCompra.Item(6, f).Value = "" Then
                            dgvOrdenCompra.Item(6, f).Value = dgvOrdenCompra.Item(1, f).Value
                        End If
                        txtCosto.Enabled = True
                        btnAgregar.Text = "Modificar"
                    Else
                        '    dgvOrdenCompra.Item(6, f).Value = ""
                        dgvOrdenCompra.Item(5, f).ReadOnly = True
                        txtCosto.Enabled = False
                        btnAgregar.Text = "Agregar"
                    End If
                Else
                    dgvOrdenCompra.Item(0, f).Value = 0
                End If
            End If
        End If
    End Sub

    Private Sub dgvOrdenCompra_CellContentClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvOrdenCompra.CellContentClick
        operaciones(e)
    End Sub

    Private Sub dgvOrdenCompra_CellContentDoubleClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvOrdenCompra.CellContentDoubleClick
        operaciones(e)
    End Sub

    Sub limpiar1()
        txtCosto.Text = "0.00"
        txtCantidad.Value = "1"
        txtUnidad.Text = ""
        txtDescripcion.Text = ""
        txtArticulo.Text = ""
    End Sub

    Private Sub btnLimpiar_Click(sender As System.Object, e As System.EventArgs) Handles btnLimpiar.Click
        limpiar1()
        txtArticulo.Focus()
    End Sub

    Private Sub btnCancelar_Click(sender As System.Object, e As System.EventArgs) Handles btnCancelar.Click
        Me.Close()
    End Sub

    Private Sub btnLimpiarGeneral_Click(sender As System.Object, e As System.EventArgs) Handles btnLimpiarGeneral.Click
        dgvOrdenCompra.Rows.Clear()
        txtCantidad.Value = "1"
        txtUnidad.Text = ""
        txtDescripcion.Text = ""
        txtArticulo.Text = ""
        lblProveedor.Text = ""
        lblFecLlegada.Text = ""
        lblFecRegistro.Text = ""
        lblCantItems.Text = ""
        txtOrdenCompra.Text = ""
        txtOrdenCompra.Focus()
    End Sub

    Private Sub btnGuardar_Click(sender As System.Object, e As System.EventArgs) Handles btnGuardar.Click
        If MsgBox("¿Desea registrar este cambio?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Mensajes al Usuario") = MsgBoxResult.Yes Then
            For Each fila As DataGridViewRow In dgvOrdenCompra.Rows
                Dim ds As DataSet = servicio1.obtenerOrdenCompraDetalle(CIA, SUC, TDO, txtOrdenCompra.Text.Trim, fila.Cells("Column1").Value)

                If ds.Tables(0).Rows.Count > 0 Then
                    servicio1.actualizarOrdenCompraDetalle(CIA, SUC, TDO, txtOrdenCompra.Text.Trim, IIf(fila.Cells("Column6").Value = "", fila.Cells("Column1").Value, fila.Cells("Column6").Value), fila.Cells("Column1").Value, fila.Cells("Column5").Value)
                Else
                    Dim codigoDetalle As String = servicio1.obtenerCodigoAutogeneradoDetalle(TDO, txtOrdenCompra.Text.Trim)
                    servicio1.registrarOrdenCompraDetalle(CIA, SUC, TDO, txtOrdenCompra.Text.Trim, codigoDetalle, fila.Cells("Column1").Value, fila.Cells("Column7").Value, fila.Cells("Column5").Value, "1")
                End If
            Next

            util.mensaje("Proceso Completado.")
            listarDetalleOrdenCompra(txtOrdenCompra.Text.Trim)
            limpiar1()
        End If
    End Sub

    Sub agregarArticulo()
        If verificarChecksMarcados() = 1 Then
            For Each fila As DataGridViewRow In dgvOrdenCompra.Rows
                If Convert.ToBoolean(fila.Cells("Column4").Value) = True Then
                    If MsgBox("¿Artículo : " & fila.Cells("Column1").Value & ", Desea reemplazarlo?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Mensajes al Usuario") = MsgBoxResult.Yes Then
                        fila.Cells("Column1").Value = txtArticulo.Text.Trim
                        fila.Cells("Column2").Value = txtDescripcion.Text.Trim
                        fila.Cells("Column3").Value = txtUnidad.Text.Trim
                        fila.Cells("Column7").Value = txtCosto.Text.Trim
                        fila.Cells("Column5").Value = txtCantidad.Text.Trim
                    End If
                End If
            Next
        Else
            If buscarArticulo(txtArticulo.Text.Trim) = True Then
                For Each fila As DataGridViewRow In dgvOrdenCompra.Rows
                    If fila.Cells("Column1").Value = txtArticulo.Text.Trim Then
                        If MsgBox("¿Artículo ya agregado, Desea actualizarlo?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Mensajes al Usuario") = MsgBoxResult.Yes Then
                            fila.Cells("Column2").Value = txtDescripcion.Text.Trim
                            fila.Cells("Column3").Value = txtUnidad.Text.Trim
                            fila.Cells("Column7").Value = txtCosto.Text.Trim
                            fila.Cells("Column5").Value = txtCantidad.Text.Trim

                            Exit For
                        End If
                    End If
                Next
            Else
                dgvOrdenCompra.Rows.Add(False, txtArticulo.Text.Trim, txtDescripcion.Text.Trim, txtUnidad.Text.Trim, txtCosto.Text.Trim, txtCantidad.Text.Trim, "")
            End If
        End If
    End Sub

    Function verificarChecksMarcados() As Integer
        Dim contador As Integer = 0
        For Each fila As DataGridViewRow In dgvOrdenCompra.Rows
            If Convert.ToBoolean(fila.Cells("Column4").Value) = True Then
                contador = contador + 1
            End If
        Next
        Return contador
    End Function

    Function buscarArticulo(codArticulo As String) As Boolean
        Dim valor As Boolean = False
        Dim contador As Integer = 0
        For Each fila As DataGridViewRow In dgvOrdenCompra.Rows
            If fila.Cells("Column1").Value = codArticulo Then
                contador = contador + 1
            End If
        Next
        If contador > 0 Then
            valor = True
        End If
        Return valor
    End Function

    Private Sub frmOrdenesCompraSIS_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    End Sub
End Class